<template>
  <div class="addSubscribe">
    <x-header class="header" :left-options="{showBack: showHeaderBack}" ref="header">预订台位</x-header>
    <div class="topHolder"></div>
    <group title="第一步（选择预订时间）：">
      <cell title="预订类型" :value="subscribeTypeText" :inline-desc='HPartyNAME'></cell>
      <datetime title="预订时间" v-model="subscribeTime" format="YYYY-MM-DD HH:mm" :start-date="startDate" :end-date="endDate" :compute-hours-function="computeHoursFunction" @on-confirm="timeCheck" :minute-list="minuteList" :required="true" placeholder="请选择"></datetime>
    </group>
    <group title="第二步（选择房台类型）：">
      <checker v-model="choosenRoomType" default-item-class="roomTypeItem" radio-required selected-item-class="roomTypeItem-selected">
        <checker-item v-for="(item,index) in roomTypeList" :key="index" :value="item.ROOMPLATFORMTYPE_ID" v-html="item.name"></checker-item>
      </checker>
    </group>
    <group title="第三步（填写资料）：">
      <x-input title="到店人手机号：" mask="99999999999" @on-blur="checkUser" v-model="phone" :max="11" text-align="right" required placeholder="点击输入"></x-input>
      <x-input title="到店人名称：" v-model="name" text-align="right" required placeholder="点击输入"></x-input>
      <x-number title="消费人数：" v-model="consumptionNum" :min="1"></x-number>
      <x-textarea title="备注（选填）：" :max="200" v-model="remark" placeholder="点击输入"></x-textarea>
    </group>
    <box gap="1rem 0.8rem">
      <x-button :gradients="['#1D62F0', '#19D5FD']" @click.native="submit" :show-loading="loadingStatus" :disabled="loadingStatus" text="提交预订"></x-button>
    </box>
  </div>
</template>

<script>
  import {Group, Cell, Datetime, dateFormat, XInput, XTextarea, XNumber, Box, XButton, Checker, CheckerItem } from 'vux'
  import {getRoomType,checkRegistered,submitSubscribe,getHolidayPartyById,getBusinessHours} from "../../api";
  import {message} from "../../common/util";

  export default {
    name:'addSubscribe',
    filters: {
      dateFormat
    },
    data(){
      return{
        paramSubscribe:this.$route.params.subscribe,
        subscribeTypeText:'普通预订',
        minuteList:['00', '10', '20', '30', '40', '50'],
        HPartyNAME:'',
        HPartyStartTime:'',
        HPartyEndTime:'',
        closeTime:[],
        openTime:[],
        loadingStatus:true,
        showHeaderBack:this.GLOBAL.showHeaderBack,
        subscribeTime:'',
        choosenRoomType: '',
        phone:'',
        name:'',
        consumptionNum:1,
        remark:''
      }
    },
    components:{
      Group,
      Cell,
      Datetime,
      XInput,
      XTextarea,
      XNumber,
      Box,
      XButton,
      Checker,
      CheckerItem
    },
    computed:{
      businessHours:{
        get(){
          return this.$store.getters.getBusinessHours
        },
        set(value){
          this.$store.commit('updateBusinessHours',value)
        }
      },
      roomTypeList:{
        get(){
          return this.$store.getters.getSubscribe_roomTypeList
        },
        set(value){
          this.$store.commit('updateSubscribe_roomTypeList',value)
        }
      },
      checkPhone(){//检查手机号正确性
        const phoneReg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/ //正则表达式验证手机号格式
        if (this.phone == '') return '手机号为空'
        if(phoneReg.test(this.phone)) return true
        else return '手机号格式错误'
      },
      startDate(){
        if(this.paramSubscribe == 'normal'){
          return dateFormat(new Date(), 'YYYY-MM-DD')
        }else {
          return this.HPartyStartTime.substring(0,10)
        }
      },
      endDate(){
        if(this.paramSubscribe == 'normal'){
          /*假如为限制营业时间前不得再预订：
            将23点改为营业时间，关闭时间改为0点；
            下面的else if不要
            */
          if(new Date().getHours() <= 23 && new Date().getHours() >= parseInt(this.closeTime[0]))
            return dateFormat(new Date().setDate(new Date().getDate() + 1), 'YYYY-MM-DD')
          else if(new Date().getHours() >= 0 && new Date().getHours() < parseInt(this.closeTime[0]))
            return dateFormat(new Date(), 'YYYY-MM-DD')
        }else {
          return this.HPartyEndTime.substring(0,10)
        }
      }
    },
    methods:{
      timeCheck(newVal){
        if(new Date(newVal.replace(/-/g,'/')).getTime() < new Date().getTime()){//replace(/-/g,'/')修复iphone解析新日期的bug
          this.subscribeTime = ''
          message({message: '所选时间已经过期！',type: 'error'})
        }
      },
      computeHoursFunction(date, isToday, generateRange){
        if(this.paramSubscribe == 'normal'){
          /*假如为限制营业时间前不得再预订：
            将23点改为营业时间，关闭时间改为0点；
            下面的else if不要
            */
          if(new Date().getHours() <= 23 && new Date().getHours() >= parseInt(this.closeTime[0])){
            if (isToday) {
              if(new Date().getHours() < parseInt(this.openTime[0])) return generateRange(parseInt(this.openTime[0]), 23)
              else return generateRange(new Date().getHours()+1, 23)
            } else return generateRange(0, parseInt(this.closeTime[0]))
          }else if(new Date().getHours() >= 0 && new Date().getHours() < parseInt(this.closeTime[0])){
            return generateRange(new Date().getHours()+1, parseInt(this.closeTime[0]))
          }
        }else {
          let hOpenTime = this.HPartyStartTime.substring(11,16).split(":"), hCloseTime = this.HPartyEndTime.substring(11,16).split(":")
          if(this.HPartyStartTime.substring(0,10) == dateFormat(new Date(date), 'YYYY-MM-DD')){
            return generateRange(hOpenTime[0], 23)
          }else if(this.HPartyEndTime.substring(0,10) == dateFormat(new Date(date), 'YYYY-MM-DD')){
            return generateRange(0, hCloseTime[0])
          }else{
            return generateRange(0, 23)
          }
        }
      },
      checkUser(){
        let phoneResult = this.checkPhone
        if (!(typeof phoneResult == 'boolean' && phoneResult)){
          message({message: phoneResult,type: 'error'})
          this.loadingStatus = false
        }else{
          checkRegistered(this.phone).then((res)=>{
            if(res.status == 'success'){
              this.name = res.data.name
            }else if(res.status == 'error') {
              this.loadingStatus = false
              message({message:res.msg,type:'error'})
              console.log('checkRegistered error info:', res.msg)
            }
          }).catch((err)=>{console.log('checkRegistered catch info:',err)})
        }
      },
      submit(){
        this.loadingStatus = true
        let phoneResult = this.checkPhone
        let reqParams = {
          subscribe: this.paramSubscribe,
          subscribeTime: this.subscribeTime,
          choosenRoomType: this.choosenRoomType,
          phone: this.phone,
          name: this.name,
          consumptionNum: this.consumptionNum,
          remark: this.remark
        }
        if (!(typeof phoneResult == 'boolean' && phoneResult)){
          message({message: phoneResult,type: 'error'})
          this.loadingStatus = false
        }else{
          if (this.subscribeTime == ''){
            message({message: '必须选择预订时间',type: 'error'})
            this.loadingStatus = false
          }else {
            if (this.name == ''){
              message({message: '到店人名称为空',type: 'error'})
              this.loadingStatus = false
            }else{
              this.$vux.confirm.show({
                title:'确认预订',
                content:'是否确认预订日期和信息？',
                onCancel: ()=> {
                  this.loadingStatus = false
                },
                onConfirm: ()=> {
                  submitSubscribe(reqParams).then((res)=>{
                    if(res.status == 'success'){
                      if(res.data.payOrNot) this.$router.push({name:'订金支付',params:{subscribeId:res.data.SUBSCRIBE_ID}})
                      else this.$router.push({path:'/subscribeServices'})
                    }else if(res.status == 'error') {
                      message({message:res.msg,type:'error'})
                      console.log('submitSubscribe error info:', res.msg)
                    }
                    this.loadingStatus = false
                  }).catch((err)=>{console.log('submitSubscribe catch info:',err)})
                }
              })
            }
          }
        }
      }
    },
    mounted(){
      let funcArray = []
      if(this.roomTypeList.length <= 0) funcArray.push(getRoomType())
      if(this.paramSubscribe == 'normal'){
        if(JSON.stringify(this.businessHours) == '{}') funcArray.push(getBusinessHours())
      }else{
        this.subscribeTypeText = '节日/派对预订'
        funcArray.push(getHolidayPartyById(this.paramSubscribe))
      }
      Promise.all(funcArray).then((res) => {
        for(let dataObj of res){
          if(dataObj.status == 'success') {
            if(dataObj.data instanceof Array){
              this.roomTypeList = dataObj.data
              //this.$store.commit('updateSubscribe_roomTypeList',dataObj.data)
            }
            if(dataObj.data.open && dataObj.data.close){
              this.businessHours = dataObj.data
              //this.$store.commit('updateBusinessHours',dataObj.data)
            }
            if(dataObj.data.PARTY_NAME){
              this.HPartyNAME = dataObj.data.PARTY_NAME
              this.HPartyStartTime = dataObj.data.START_DATETIME
              this.HPartyEndTime = dataObj.data.END_DATETIME
            }
          }else if(dataObj.status == 'error'){
            message({message: dataObj.msg, type: 'error'})
            console.log('getRoomType or getBusinessHours or getHolidayPartyById error info:', dataObj.msg)
          }
        }
      }).then(() => {
        this.choosenRoomType = this.roomTypeList[0].ROOMPLATFORMTYPE_ID
        this.closeTime = this.businessHours.close.split(":")
        this.openTime = this.businessHours.open.split(":")
        this.loadingStatus = false
        this.$store.commit('updateLoadingStatus',{isLoading:false})
      }).catch((err) => {console.log('getRoomType or getBusinessHours or getHolidayPartyById catch info:', err)})
    }
  }
</script>

<style lang="scss">
  .addSubscribe{
    .vux-checker-box{
      padding:0.5rem 0;
      display: flex;flex-wrap:wrap;
      .roomTypeItem {margin: 0.5rem 0 0.5rem 1rem;width: 100px;min-height: 42px;line-height: 20px;font-size: 14px;
        display: flex;justify-content: center;align-items: center;
        text-align: center;border-radius: 3px;border: 1px solid #ccc;background-color: #fff;}
      .roomTypeItem-selected {background: #ffffff url(../../assets/images/checker/active.png) no-repeat right bottom;border-color: #ff4a00;}
    }
  }
</style>
